package com.sy.olddriver.service.impl;

import com.sy.olddriver.constant.AppConstant;
import com.sy.olddriver.dao.UserDao;
import com.sy.olddriver.dao.impl.UserDaoImpl;
import com.sy.olddriver.dto.Result;
import com.sy.olddriver.entity.User;
import com.sy.olddriver.exception.OldDriverException;
import com.sy.olddriver.service.CartService;
import com.sy.olddriver.service.HistoryService;
import com.sy.olddriver.service.UserService;
import com.sy.olddriver.utils.HttpUtils;
import com.sy.olddriver.utils.ParamUtils;
import com.sy.olddriver.utils.RedisUtils;
import com.sy.olddriver.vo.RegistParam;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;

/**
 * UserService接口的实现类
 *
 * @author Administrator
 */
public class UserServiceImpl implements UserService {
    private UserDao userDao = new UserDaoImpl();

    private CartService cartService = new CartServiceImpl();

    private HistoryService historyService = new HistoryServiceImpl();

    @Override
    public Result getUserByUserName(String userName) {
        Result result = new Result();
        try {
            User user = userDao.getUserByUserName(userName);
            if (null != user) {
                user.setPwd(null);
                result.setData(user);
            } else {
                throw new OldDriverException("未找到相关的用户");
            }
        } catch (OldDriverException e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrMsg(e.getMessage());
        }
        return result;
    }

    @Override
    public Result getUserByPhone(String phone) {
        Result result = new Result();
        try {
            User user = userDao.getUserByPhone(phone);
            if (null != user) {
                user.setPwd(null);
                result.setData(user);
            } else {
                throw new OldDriverException("未找到相关的用户");
            }
        } catch (OldDriverException e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrMsg(e.getMessage());
        }
        return result;
    }

    @Override
    public Result regist(RegistParam registParam, String corValidateCode) {
        Result result = new Result();
        try {

            //用户名不能为空
            String userName = registParam.getUserName();
            if (StringUtils.isBlank(userName)) {
                throw new OldDriverException("用户名不能为空");
            }
            //用户名不能重复
            if (null != userDao.getUserByUserName(userName)) {
                throw new OldDriverException("用户名不能重复");
            }
            //密码不能为空
            String pwd = registParam.getPwd();
            String pwdConfirm = registParam.getPwdConfirm();
            if (StringUtils.isBlank(pwd) || StringUtils.isBlank(pwdConfirm)) {
                throw new OldDriverException("密码不能为空");
            }
            //两次输入的密码要一致
            if (!StringUtils.equals(pwd, pwdConfirm)) {
                throw new OldDriverException("两次输入的密码不一致");
            }
            //手机号不能为空
            String phone = registParam.getPhone();
            if (StringUtils.isBlank(phone)) {
                throw new OldDriverException("手机号不能为空");
            }
            //手机号的格式校验
            if (!phone.matches(AppConstant.PHONE_REGEX)) {
                throw new OldDriverException("手机号格式不合法");
            }
            //一个手机号不能重复注册
            if (null != userDao.getUserByPhone(phone)) {
                throw new OldDriverException("同一个手机号不能重复注册");
            }
            //输入的验证码不能为空
            String inputValidateCode = registParam.getValidateCode();
            if (StringUtils.isBlank(inputValidateCode)) {
                throw new OldDriverException("验证码不能为空");
            }
            //输入的验证码必须和发送的要一样
            if (!StringUtils.equals(inputValidateCode, corValidateCode)) {
                throw new OldDriverException("验证码不正确");
            }

            //添加用户信息到数据库中
            User user = new User();
            user.setUserName(userName);
            user.setPwd(DigestUtils.md5Hex(pwd));
            user.setPhone(phone);
            if (!userDao.addUser(user)) {
                throw new OldDriverException("新增用户信息失败");
            }
        } catch (OldDriverException e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrMsg(e.getMessage());
        }
        return result;

    }

    @Override
    public Result login(String userName, String userPwd) {
        Result result = new Result();
        try {
            //判断用户名和密码是否为空
            if (StringUtils.isBlank(userName) || StringUtils.isBlank(userPwd)) {
                throw new OldDriverException("用户名和密码不能为空");
            }
            //判断用户信息在数据库中是否是合法的信息
            User user = userDao.getUserByUserName(userName);
            //用户名错误
            if (null == user) {
                throw new OldDriverException("用户名有误");
            } else {
                //密码有误
                if (!StringUtils.equals(user.getPwd(), DigestUtils.md5Hex(userPwd))) {
                    throw new OldDriverException("密码错误");
                }
                //登录成功
                else {
                    user.setPwd(null);
                    result.setData(user);

                    //1.合并浏览历史的记录
                    historyService.mergeHistory(user.getId());

                    //2.合并购物车记录
                    cartService.mergeCart(user.getId());
                }
            }

        } catch (OldDriverException e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrMsg(e.getMessage());
        }
        return result;
    }

    @Override
    public Result updateUser(String content, String updateType, Integer userId) {
        Result result = new Result();
        try {
            //如果前端传递的updateType不合法，也需要校验
            if (!AppConstant.VALID_UPDATE_TYPES.contains(updateType)) {
                throw new OldDriverException("无法完成更新操作");
            }
            //如果为0，进行名字的校验
            if (AppConstant.UPDATE_TYPE_NAME.equals(updateType)) {
                //用户名判空
                if (StringUtils.isBlank(content)) {
                    throw new OldDriverException("用户名不能为空");
                }
                //用户名判断不能重复
                if (null != userDao.getUserByUserName(content)) {
                    throw new OldDriverException("用户名已经被占用");
                }
            }
            //如果为1，进行手机号的校验
            if (AppConstant.UPDATE_TYPE_PHONE.equals(updateType)) {
                //判空校验
                if (StringUtils.isBlank(content)) {
                    throw new OldDriverException("手机号不能为空");
                }
                //正则校验
                if (!content.matches(AppConstant.PHONE_REGEX)) {
                    throw new OldDriverException("手机号格式不合法");
                }
                //相同的手机号不能重复使用
                if (null != userDao.getUserByPhone(content)) {
                    throw new OldDriverException("当前手机号已经被占用");
                }
            }
            //TODO:其它字段的更新
            //将数据更新到数据库中去
            if (!userDao.updateUser(content, updateType, userId)) {
                throw new OldDriverException("用户信息更新失败");
            } else {
                User user = userDao.getUserById(userId);
                user.setPwd(null);
                //同步Redis中的用户数据
                RedisUtils.set(AppConstant.USER_TOKEN_REDIS_PREFIX + HttpUtils.getCookie(AppConstant.USER_TOKEN_COOKIE_NAME), user);
            }
        } catch (OldDriverException e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrMsg(e.getMessage());
        }
        return result;
    }

    @Override
    public Result getUserInfo(Integer userId) {
        Result result = new Result();
        try {
            //从数据库中查询用户的全部信息
            User user = userDao.getUserById(userId);
            user.setPwd(null);
            result.setData(user);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrMsg(e.getMessage());
        }
        return result;

    }


}
